import {useEffect, useState, useRef} from 'react'
import { searchApi } from './api'
// 自定义 hook 数据层
export default function useFetch() {
  const str = useRef('')
  const [param, setParam] = useState({})
  const [list, setList] = useState<string[]>([])
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  function getList() {
    searchApi(str.current).then(res => {
      setList(res)
      setLoading(false)
      setError('')
    }).catch(err => {
      setLoading(false)
      setError(err)
    })
  }

  useEffect(() => {
    loading && getList()
  }, [loading])

  return { str, list, error, loading, setLoading, setParam }
}